﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ReactReduxTool.Utils;
using ReactReduxTool.app;
using ReactReduxTool.Model;
using System.Threading;
using System.IO;
using ReactReduxTool.UI;

namespace ReactReduxTool.UI
{

    public partial class FrmMain : Form
    {

        private Point mousePos;
        private bool isMouseDown;
        private string mTargetPath;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            FrmInit frmInit = new FrmInit();
            var result = frmInit.ShowDialog();
            if (result == DialogResult.Yes)
            {
                txtTargetPath.Text = frmInit.TargetPath;
                mTargetPath = txtTargetPath.Text;
                frmInit.Close();
                AppCtx.Init(configs => InitNPMCommandRows(configs));
            }
            else
            {
                frmInit.Close();
                this.Close();
            }
        }

        /// <summary>
        /// 初始化配置命令行显示
        /// </summary>
        /// <param name="configs"></param>
        private void InitNPMCommandRows(List<ConfigItemInfoEntry> configs)
        {
            for (int i = 0; i < configs.Count; i++)
            {
                ConfigItemInfoEntry item = configs[i];
                DataGridViewRow row = new DataGridViewRow();
                for (int j = 0; j < 4; j++)
                {
                    switch (j)
                    {
                        case 0://文字列
                            string type = item.Type == 1 ? "DEV" : (item.Type == 2 ? "PUB" : "GLOBAL");
                            DataGridViewTextBoxCell txtCell = new DataGridViewTextBoxCell();
                            txtCell.Value = "[" + type + "] " + item.Name;
                            txtCell.Tag = item.Command;//记录命令行
                            row.Cells.Add(txtCell);
                            txtCell.ReadOnly = true;
                            break;
                        case 1://是否是全局依赖
                            DataGridViewCheckBoxCell cbCell1 = new DataGridViewCheckBoxCell();
                            cbCell1.Value = false;
                            row.Cells.Add(cbCell1);
                            break;
                        case 2://是否是开发依赖
                            DataGridViewCheckBoxCell cbCell2 = new DataGridViewCheckBoxCell();
                            cbCell2.Value = false;
                            row.Cells.Add(cbCell2);
                            break;
                        case 3://是否是Pub依赖
                            DataGridViewCheckBoxCell cbCell3 = new DataGridViewCheckBoxCell();
                            cbCell3.Value = false;
                            row.Cells.Add(cbCell3);
                            break;
                    }

                }
                lvNpm.Rows.Add(row);
            }
        }

        private void titlebar_MouseDown(object sender, MouseEventArgs e)
        {
            mousePos = Cursor.Position;
            isMouseDown = true;
        }

        private void titlebar_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
            this.Focus();
        }

        private void titlebar_MouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown && e.Button == MouseButtons.Left)
            {
                Point tempPos = Cursor.Position;
                Location = new Point(Location.X + (tempPos.X - mousePos.X), Location.Y + (tempPos.Y - mousePos.Y));
                mousePos = Cursor.Position;
            }
        }

        private void imgAppExit_Click(object sender, EventArgs e)
        {
            DialogUtil.ShowExitAlertDialog(() => this.Close());
        }

        private void lvNpm_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            DataGridView grid = sender as DataGridView;
            if (grid != null)
            {
                grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void lvNpm_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView grid = sender as DataGridView;
            if (grid != null && e.RowIndex >= 0)
            {
                string npmCommand = "npm install " + lvNpm.Rows[e.RowIndex].Cells[0].Tag.ToString(); ;
                switch (grid.Columns[e.ColumnIndex].Name)
                {
                    case "isGlobal":
                        npmCommand += " -g";
                        break;
                    case "isDev":
                        npmCommand += " --save-dev";
                        break;
                    case "isPub":
                        npmCommand += " --save";
                        break;
                }
                txtMsg.Text = "信息: 正在执行命令'" + npmCommand + "'...";
                txtConsole.AppendText(txtMsg.Text + "\r\n");
                lvNpm.Enabled = false;
                new Thread(() =>
                {
                    CmdUtil.GetInstance().RunCmd("cd " + mTargetPath + " \r\n" + npmCommand, result =>
                    {
                        Invoke((MethodInvoker)delegate
                        {
                            txtMsg.Text = "信息: 命令行'" + npmCommand + "'执行完成";
                            txtConsole.AppendText(result + "\r\n" + txtMsg.Text + "\r\n\r\n\r\n");
                            txtConsole.SelectionStart = txtConsole.TextLength;
                            txtConsole.Focus();
                            lvNpm.Enabled = true;
                        });
                    });
                }).Start();
            }
        }

        private void imgInit_Click(object sender, EventArgs e)
        {
            txtMsg.Text = "信息：开始初始化配置项目...";
            txtConsole.AppendText(txtMsg.Text);
            AppCtx.FinishConfigTask(mTargetPath, () =>
            {
                Invoke((MethodInvoker)delegate
                {
                    txtMsg.Text = "信息: 项目初始化配置完成";
                    txtConsole.AppendText("\r\n" + txtMsg.Text + " \r\n\r\n");
                });
            });
        }

    }
}
